using Microsoft.Extensions.Options;
using Vin.Extension.SqlSugar.Options;
using Vin.Tool.AspNetCore.Service;
using Vin.Tool.AspNetCore.Singleton;
using Vin.Tool.Core.BasicTypeCategory;
using Vin.Tool.Core.EncryptCategory;

namespace Vin.Extension.SqlSugar.DataExecute.EncryptAdapter;

public class VinAesSugarEncryptAdapter : VinBaseService, IVinSugarBaseEncryptAdapter
{
    private IOptionsMonitor<SugarAesEncryptOption> _encryptOption;

    private string Key => _encryptOption.CurrentValue.Key!;

    private string Iv => _encryptOption.CurrentValue.Iv!;

    public VinAesSugarEncryptAdapter()
    {
        _encryptOption = VinApp.GetOptionsMonitor<SugarAesEncryptOption>();
    }

    /// <summary>
    /// 加密
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public string Encrypt(string value)
    {
        try
        {
            // 判断是否是base64
            if (value.IsBase64()) return value;
            return AesEncryptTool.AesEncrypt(value, Key, Iv, false);
        }
        catch
        {
            return value;
        }
    }

    /// <summary>
    /// 加密
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static string ToEncrypt(string value)
    {
        return new VinAesSugarEncryptAdapter().Encrypt(value);
    }

    /// <summary>
    /// 解密
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public string Decrypt(string value)
    {
        try
        {
            return AesEncryptTool.AesDecrypt(value, Key, Iv, false);
        }
        catch
        {
            return value;
        }
    }

    /// <summary>
    /// 解密
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static string ToDecrypt(string value)
    {
        return new VinAesSugarEncryptAdapter().Decrypt(value);
    }
}